package com.ss.android.common.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.bytedance.common.utility.NetworkType;

public final class NetworkStatusMonitor {
    final Context mContext;
    public NetworkType mCurrrentNetworkType;
    private boolean mReceiverOn;
    private BroadcastReceiver mNetworkStateReceiver;

    public NetworkStatusMonitor(Context context) {
        this.mReceiverOn = false;
        this.mCurrrentNetworkType = NetworkType.MOBILE;
        this.mContext = context;
        this.registerNetworkStateReceiver();
    }

    public final void onPause() {
        if (this.mReceiverOn) {
            this.mReceiverOn = false;
            this.mContext.unregisterReceiver(this.mNetworkStateReceiver);
            this.mNetworkStateReceiver = null;
        }
    }

    public final void onDestroy() {
        if (this.mReceiverOn) {
            this.mReceiverOn = false;
            this.mContext.unregisterReceiver(this.mNetworkStateReceiver);
            this.mNetworkStateReceiver = null;
        }
    }

    public final void registerNetworkStateReceiver() {
        if (!this.mReceiverOn) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            this.mNetworkStateReceiver = new BroadcastReceiver() {
                @Override
                public final void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                        try {
                            mCurrrentNetworkType = NetworkUtils.getNetworkType(mContext);
                        } catch (Exception ex) {
                            Log.w("NetworkStatusMonitor", "receive connectivity exception: " + ex);
                        }
                    }
                }
            };
            this.mReceiverOn = true;
            try {
                this.mContext.registerReceiver(this.mNetworkStateReceiver, intentFilter);
            } catch (Throwable throwable) {
            }
        }
        this.mCurrrentNetworkType = NetworkUtils.getNetworkType(this.mContext);
    }

    public final boolean isWifiOn() {
        return NetworkType.WIFI == this.mCurrrentNetworkType;
    }

    public final boolean isNetworkOn() {
        return NetworkType.NONE != this.mCurrrentNetworkType;
    }
}

